import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart'hide Action;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:oktoast/oktoast.dart';
import 'package:school_safe_teacher/base/base_entity.dart';
import 'package:school_safe_teacher/constans/all_info.dart';
import 'package:school_safe_teacher/me/entity/userEntity.dart';
import 'package:school_safe_teacher/network/dio_api.dart';
import 'package:school_safe_teacher/network/http_api.dart';


import 'action.dart';
import 'state.dart';

Effect<ChangeUserInfoState> buildEffect() {
  return combineEffects(<Object, Effect<ChangeUserInfoState>>{
    Lifecycle.initState: _init,
    ChangeUserInfoAction.changeInfo: _onChangeInfo,
  });
}

void _init(Action action, Context<ChangeUserInfoState> ctx) {
  if (AllInfo.instance.token.isNotEmpty) {
    UserEntity userInfoEntity = AllInfo.instance.userEntity;
    ctx.state..info = userInfoEntity.content;
    ctx.state.infoController..text = userInfoEntity.content;
    ctx.dispatch(ChangeUserInfoActionCreator.onAction());
  }
}

void _onChangeInfo(Action action, Context<ChangeUserInfoState> ctx) {
  Map<String, String> params = Map();
  params["field"] = "content";
  params["value"] = ctx.state.info;
  DioApi.instance.asyncRequestNetwork<BaseEntity>(
      Method.post, HttpApi.EDIT_USER_INFO,ctx.context,
      params: params, onStart: () {
    println('请求开始');
    EasyLoading.show();
  }, onSuccess: (dynamic t) {
    UserEntity userInfoEntity = AllInfo.instance.userEntity;
    userInfoEntity.content = ctx.state.info;
    AllInfo.instance.setUserEntity(userInfoEntity);
    showToast("修改成功");
    ctx.broadcast(ChangeUserInfoActionCreator.onChangeInfoSuccess());
    Navigator.of(ctx.context).pop(1);
  }, onError: (String msg) {
    println('请求报错 msg:$msg');
    showToast(msg);
  }, onDone: () {
    EasyLoading.dismiss();
  }, isList: false);
}
